const query = require("../db/mysql");
const {success,error} = require ('../model/model')
class Cart {
    getCartList = async (ctx) => {
        // 获取购物车列表
        const {user_id} = ctx.query;
        const sql = `select * from carts where user_id="${user_id}"`
        const data = await query(sql);
        // 返回一个由promise组成的数组
        const allP = data.map((item)=> {
            return new Promise(async(resolve,reject)=>{
               try{
                    const res = await query(`select * from shops where id="${item.shop_id}"`)
                    resolve(res)
               }catch(err){
                   reject(err)
               }
            })
        })
        const shops = await Promise.all(allP) // Promise.all 接收一个由promise组成的数组  当所有的promise都resolve之后 返回resolve
        // 只要有一个reject则返回reject
        const newData = data.map((item,index) => {
            return { ...shops[index][0], ...item}
        })
        ctx.body = success(newData);
    }
    addToCart = async(ctx) => {
        const {user_id,shop_id} = ctx.request.body;
        // 如果这个商品已经被加购了 则不执行添加 而是修改count
        // 1. 判断商品是否存在
        const isHaveSql = `select * from carts where shop_id="${shop_id}" and user_id="${user_id}"`
        const isHave = await query(isHaveSql);
        let data;
        if(isHave.length) {
            // 已有 执行更新count
            const sql = `update carts set count="${isHave[0].count+=1}" where id="${isHave[0].id}"`
            data = await query(sql)
        } else {
            // 没有 第一次加入购物车
            const sql = `insert into carts(user_id,shop_id,count) values("${user_id}","${shop_id}","${1}")`
            data = await query(sql)
        }
        if(data.affectedRows===1){
            ctx.body = success('加入成功')
        } else {
            ctx.body = error("加入失败")
        }
    }
    delCart = async(ctx) => {
        const {id} = ctx.params
        const sql = `delete from carts where id="${id}"`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('删除成功')
        } else {
            ctx.body = error('删除失败')
        }
    }
    setCartCount = async(ctx) => {
        const {id, count} = ctx.request.body;
        const sql = `update carts set count="${count}" where id=${id}`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('修改成功')
        } else {
            ctx.body = error('修改失败')
        }
    }
}

module.exports = new Cart()